using System;
using System.Collections.Generic;
using System.Linq;
using csvviewer.logic.data;

namespace csvviewer.logic
{
	public class Normalize_columns
	{
		public void Process(PageOfRecords page)
		{
			var colWidth = Find_max_col_width (page.Records);
			var normalizedRecords = Pad_column_values (page.Records, colWidth);
			this.Page(new PageOfRecords{Records=normalizedRecords, PageInfo=page.PageInfo});	
		}
		
		public event Action<PageOfRecords> Page;
		
		
		static List<int> Find_max_col_width (IEnumerable<CsvRecord> records)
		{
			var colWidth = new List<int>();
			for(var col = 0; col < records.First().Values.Length; col++)
			{
				colWidth.Add(records.Select(r => r.Values[col].Length).Max());
			}
			return colWidth;
		}
		
		
		static IEnumerable<CsvRecord> Pad_column_values (IEnumerable<CsvRecord> records, List<int> colWidth)
		{
			foreach(var r in records)
			{
				var normalizedRecord = new CsvRecord() { Values = new string[records.First().Values.Length] };
				for(var col = 0; col < records.First().Values.Length; col++)
					normalizedRecord.Values[col] = r.Values[col].PadRight(colWidth[col]);
				yield return normalizedRecord;
			}
		}
	}
}

